package com.example.petstore.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.Item;
import com.example.petstore.domain.LineItem;
import com.example.petstore.domain.Order;
import com.example.petstore.mapper.ItemMapper;
import com.example.petstore.mapper.LineItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("lineItemService")
public class LineItemService {
    @Autowired
    private LineItemMapper lineItemMapper;


    public List<Map.Entry<String, Integer>> calculateTotalQuantityAndSort() {
        LambdaQueryWrapper<LineItem> queryWrapper = new LambdaQueryWrapper<>();
        List<LineItem> lineItems = lineItemMapper.selectList(queryWrapper);
        List<LineItem> lineItems1 = new ArrayList<>();
//        判断item是否已经被删除
        for(LineItem lineItem:lineItems){
            lineItem.getItemid();
            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("itemid", lineItem.getItemid());
            List res = lineItemMapper.selectList(queryWrapper1);
            if(res.size() > 0){
                lineItems1.add(lineItem);
            }
        }

        Map<String, Integer> itemQuantityMap = lineItems1.stream()
                .collect(Collectors.groupingBy(LineItem::getItemid, Collectors.summingInt(LineItem::getQuantity)));

        List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(itemQuantityMap.entrySet());
        sortedList.sort(Map.Entry.<String, Integer>comparingByValue().reversed());

        return sortedList;
    }

    public List<LineItem> getLineItemsByOrderId(int orderId) {
        return lineItemMapper.selectList(new QueryWrapper<LineItem>().eq("orderid", orderId));
    }
}
